import React, {forwardRef, useEffect, useImperativeHandle, useRef} from 'react';
import { useState } from 'react';
import {
    Drawer,
    Grid,
    Tag,
    Tabs,
    Tree,
    Input,
    Button,
    Pagination,
    Descriptions,
    Trigger,
    Skeleton,
    Menu,
    Dropdown,
    Upload,
    Modal,
    Progress,
    Popconfirm,
    Popover,
    Message,
    Space,
    Link

} from '@arco-design/web-react';
import { IconPlus,IconAlignLeft,IconDelete,IconDown,IconPlusCircle } from '@arco-design/web-react/icon';
const token = localStorage.getItem('userToken');


import styles from './style/detail.module.less'
const Row = Grid.Row;
const Col = Grid.Col;
const TabPane = Tabs.TabPane;
const TreeNode = Tree.Node; // 从treedata 生成 treenode
const InputSearch = Input.Search;

import {
    getDicValueApi,
    getSchCourse,
    getSchCourseTree,
    getSchCourseResourceBySchCourseKnowledgeId,
    schCourseResourceInsert,
    download,
    schCourseResourceUpdate,
    schCourseRef,
    getLessonAllApi,
    schCourseRefInsert,
    schCourseRefInsertSupport,
    schCourseRefInsertKnowledgeDependsFirst,
    schCourseRefInsertKnowledgeDependsSecond,
    schCourseRefInsertKnowledgeApplyFirst, schCourseRefInsertKnowledgeApplySecond, del, searchCourseKnowledge,searchCourseKnowledgeSecond,
    addKnowledgeApi,editKnowledgeApi,deleteKnowledgeApi,getKnowledgeApi,editSectionApi,addSectionApi,deleteSectionApi,getSectionApi
} from "@/request/api";
import Map from '@/pages/knowledgeCheck/list/map'

const Detail = forwardRef((props:{
    openMenu

},ref)=>{

    const mapRef = useRef(null);
    const [visible, setVisible] = useState(false);
    const [defaultActiveTab, setDefaultActiveTab] = useState('1');
    const [visible2, setVisible2] = useState(false);
    const [modelVisible, setModelVisible] = useState(false);
    const [info, setInfo] = useState({ schCourseId: '',bizType:undefined,id:'',name:''});
    //根据bizType判断传递参数  0课程 1章节 2一级知识节点 3二级知识节点
    const bizTypeList = ['schCourseId','schCourseChapterId','schCourseKnowledgeFirstId','schCourseKnowledgeSecondId']
    const [semester, setSemester] = useState([]); //学期
    const [courseSystemType, setCourseSystemType] = useState([]); //课程体系
    const [newName,setNewName] = useState("")//修改的文件名字
    const detailRef = useRef(null)

    const dropList = (
        <Menu>
            <Menu.Item key='1'>仅查看此节点</Menu.Item>
            <Menu.Item key='2'>包含全部子节点</Menu.Item>
        </Menu>
    );
    const [schCourse, setSchCourse] = useState({
        name: '', introduce: "",createTime:"",createByUser:[],
        isRequire: undefined
    })
    const [treeData, setTreeData] = useState([]);
    const [queryType, setQueryType] = useState('1');
    const [itemIndex,setItemIndex] = useState(undefined);
    const [isEdit,setIsEdit] = useState(false);
    //模态框挂载父节点
    const refWrapper = useRef(null);


    //文件类型图标list
    const fileTypeIconList = [
        { type: '', src: require('../img/file.png'), name: '全部资料' },
        { type: 'word', src: require('../img/word.png'), name: '文档' },
        { type: 'mp4', src: require('../img/video.png'), name: '视频' },
        { type: 'jpg', src: require('../img/image.png'), name: '图片' },
        { type: 'zip', src: require('../img/zip.png'), name: '压缩包' },
        { type: 'other', src: require('../img/default.png'), name: '其他' }
    ]
    // 资源上传list
    const [uploadList, setUploadList] = useState([

    ]);
    //目录导航右侧表格数据
    const [data, setData] = useState([]);
    //左侧树显示
    const generatorTreeNodes = (treeData) => {
        return treeData.map((item) => {
            const { children, id,name, ...rest } = item;
            return (
                <Tree.Node key={id}  title={name} dataRef={item}>
                    {children ? generatorTreeNodes(item.children) : null}
                </Tree.Node>
            );
        });
    };
    //分页资料库分页
    const [page, setPage] = useState({
        pageNum: 1,
        pageSize: 30,
        name:'',
        suffixList:[],

    });
    const [resource, setResource] = useState({
        total: 0,
        list: [],
    });


    // 先修课程 支撑课程 应用关系知识  依赖关系知识
    const [xxkcList, setxxkcList] = useState({
        total: 0,
        list: [],
    });
    const [xxkcpage, setxxkcPage] = useState({
        pageNum: 1,
        pageSize: 10,
    });
    const [zckcList, setzxkcList] = useState({
        total: 0,
        list: [],
    });
    const [zckc, setzckcPage] = useState({
        pageNum: 1,
        pageSize: 10,
    });
    const [yygxzxList, setyygxzxList] = useState({
        total: 0,
        list: [],
    });
    const [yygxzx, setyygxzx] = useState({
        pageNum: 1,
        pageSize: 10,
    });
    const [ylgxzxList, setylgxzxList] = useState({
        total: 0,
        list: [],
    });
    const [ylgxzx, setylgxzxPage] = useState({
        pageNum: 1,
        pageSize: 10,
    });





    //获取树并将当前焦点聚焦带树
    const treeInit = () => {
        getSchCourseTree({schCourseId:info.schCourseId}).then(res => {
            setTreeData(res.data);
            //TODO  接口尚未返回全部数据无法聚焦到指定树

        })
    }
    //组件传递方法
    useImperativeHandle(ref, () => ({
        setVisible: (newVal) => {
            setVisible(newVal);
        },
        setInfo: (newVal) => {
            setInfo(newVal);
        },

    }));



    //初始化
    useEffect(() => {
        //字典
        fetchSemester()
        fetchCourseSystemType()
        console.log(info,'info')
        if (info.schCourseId){
            getCourseInfo()
            treeInit()
            requestData()
            if (info.bizType===2||info.bizType===3){
                yygxzsInit()
                ylzsgxInit()
            }else {
                xxkcInit()
                zckcInit()
            }
        }

    }, [info]);


    //树图右侧详情
    const getCourseInfo = () => {

        getSchCourse({id: info.schCourseId}).then(res => {
            const arr = [{
                label: '课程名称',
                value: res.data.name,
            },
                {
                    label: '所属院校',
                    value: res.data.sysSpecialityDeptList.map((element) => element.sysDept.name)?.join('/')
                },
                {
                    label: '所属专业',
                    value: res.data.sysSpecialityDeptList.map((element) => element.sysSpecialityDept.name)?.join('/')
                },
                {
                    label: '是否必修',
                    value: res.data.isRequire === 0 ? '不必修' : '必修',
                },
                {
                    label: '学期',
                    value: semester.find(e=>e.key===res.data.semester)?.value,
                },
                {
                    label: '课程体系',
                    value: courseSystemType.find(e=>e.key===res.data.courseSystemType)?.value,
                },
                {
                    label: '课程学时',
                    value: res.data.classHour,
                },
                {
                    label: '课程学分',
                    value: res.data.credit,
                },
                {
                    label: '课程简介',
                    value: res.data.introduce,
                },
                {
                    label: '课程教师',
                    value: res.data.teacherList.map((element) => element.name)?.join('/')
                },
            ]
            setSchCourse(res.data)
            setData(arr)


        }).catch(err => {
            console.log(err)})


    }

    //字典
    const fetchSemester = () => {
        getDicValueApi({ code: 'semester' })
            .then((res) => {
                const { data } = res;
                setSemester(data);
            })
            .catch((e) => {
                console.log(e);
            });
    };
    const fetchCourseSystemType = () => {
        getDicValueApi({ code: 'course_system_type' })
            .then((res) => {
                const { data } = res;
                setCourseSystemType(data);
            })
            .catch((e) => {
                console.log(e);
            });
    };


    //获取资料列表数据
    const  requestData = ()=>{

        const params = {
            bizType: info.bizType,
            [bizTypeList[info.bizType]]:info.id,
            ...page
        }
        getSchCourseResourceBySchCourseKnowledgeId(params).then(res=>{
            setResource(res.data)
        })


    }



    //资料左侧菜单
    function menuLeft(){
        return(
            <>

                {
                    Object.values(fileTypeIconList).map((item,index)=>(

                        <div className={styles.leftMenuItems} key={index} onClick={()=>{
                            if (item.type!==''){
                                setPage((prevPage) => ({
                                    ...prevPage,
                                    suffixList: [item.type]
                                }));
                            }else {
                                setPage((prevPage) => ({
                                    ...prevPage,
                                    suffixList: []
                                } ))
                            }
                        }}>
                            <img src={item.src}/>
                            <div  style={{color:(page.suffixList[0]===item.type||(item.name==='全部资料'&&page.suffixList.length===0))?'#165DFF':''}}>{item.name}</div>
                        </div>
                    ))
                }

            </>
        )}

    //信息改变监听
    useEffect(() => {
        requestData();
    }, [page]);
    //信息改变监听
    useEffect(() => {
        xxkcInit()
    }, [xxkcpage]);


    //附件模态框
    useEffect(()=>{
        setModelVisible(uploadList.length>0)
    },[uploadList])


    const text = ["课程", "章节", "一级知识", "二级知识", "资料"]


    const openMenu = (record) => {

        setVisible(false)
        const  info = {
            schCourseId: record.bizId ,
            bizType: record.bizType,
            id: record.id
        }
        props.openMenu(info)

    }
    //资料库中间列表
    function list(){




        function formatDateString(dateTimeString) {
            const parts = dateTimeString.split(" "); // 将日期和时间分割成两部分
            const datePart = parts[0]; // 获取日期部分，即 "YYYY-MM-DD"

            const dateParts = datePart.split("-"); // 将日期部分按照 "-" 分割成年、月、日
            const year = dateParts[0]; // 年份，即 "YYYY"
            const month = dateParts[1]; // 月份，即 "MM"
            const day = dateParts[2]; // 日，即 "DD"

            const formattedDate = year + "/" + month + "/" + day; // 拼接成所需的格式

            return formattedDate;
        }




        const items = [];

        for (let i = 0; i < resource.list.length; i++) {
            items.push(
                <Trigger
                    key={i}
                    showArrow
                    trigger='hover'
                    position='right'
                    popupAlign={{
                        right: [30, 50],
                    }}
                    onVisibleChange={(visible) => {
                        if (!visible) setIsEdit(visible)

                        // console.log(newName!=="",newName!==resource.list[i].name.substring(0,resource.list[i].name.indexOf('.')))
                        if (newName!==""&&newName!==resource.list[i].name.substring(0,resource.list[i].name.indexOf('.'))){
                            const params = {...resource.list[i]}
                            params.name = newName+`.${params.suffix}`
                            schCourseResourceUpdate(params).then(res=>{
                                requestData()
                                setNewName("")
                            })
                        }






                    }}
                    popup={() => (
                        <div className={styles.trigger}>
                            <div>详细信息</div>
                            <div style={{display:"flex",whiteSpace:'nowrap',alignItems:'center'}}>名称:
                                {isEdit&&(<Input
                                    id={resource.list[i].id}
                                    type="text"
                                    defaultValue={newName}
                                    onChange={(e) => {
                                        setNewName(e)
                                    }}
                                ></Input>)}
                                {!isEdit&&(<div>{resource.list[i].name.substring(0,resource.list[i].name.indexOf('.'))}</div>)}
                            </div>
                            <div>格式: {resource.list[i].suffix}</div>
                            <div>大小: {(resource.list[i].size/(1024**2))?.toFixed(3)}MB</div>
                            <div>上传时间: {formatDateString(resource.list[i].createTime)}</div>
                            <div>归属节点: {resource.list[i].belongMsg.name}</div>
                            <div>节点类型: {text[resource.list[i].belongMsg.type]}</div>
                        </div>

                    )}
                >
                    <div style={{position:'relative'}} onMouseLeave={()=>{setItemIndex(undefined)}}>
                        <div className={styles.gridItem}  onClick={()=>{setItemIndex(i)}} >
                            <div>
                                <img src={fileTypeIconList.find(e=>e.type==resource.list[i].suffix)?.src||fileTypeIconList[5].src} />
                                <div style={{overflow: 'hidden',
                                    whiteSpace: 'nowrap',
                                    textOverflow: 'ellipsis',width:'150px'}}>
                                    {resource.list[i].name.substring(0,resource.list[i].name.indexOf('.'))}
                                </div>
                            </div>
                            <div>
                                <img src={require('../img/download.png')}/>
                            </div>
                        </div>
                        {itemIndex === i&&(<div className={styles.triggerDown} >
                            <div onClick={ ()=>{

                                // 创建URL对象
                                const url = 'http://101.200.84.209:10000/api/fileStore/download?key='+resource.list[i].key
                                // 创建a标签
                                const a = document.createElement("a");
                                a.href = url;
                                // 触发下载
                                a.click();
                                // 释放内存
                                URL.revokeObjectURL(url);
                            }
                            }>下载</div>
                            <div onClick={()=>{
                                setNewName(resource.list[i].name.substring(0,resource.list[i].name.indexOf('.')))
                                setIsEdit(true)
                            }}>重命名</div>
                        </div>)}
                    </div>
                    {/*</Trigger>*/}
                </Trigger>
            );


















            {/*<div>*/}
            {/*    <img width={30} height={30} src={require('../img/database.png')}/>*/}
            {/*</div>*/}
            {/*<div>*/}
            {/*    <div>资料名称资料名称资料名称资料名称资料名称资料名称</div>*/}
            {/*    <div>*/}
            {/*        <div>更新时间：2023年8月30日 23:07:14</div>*/}
            {/*        <div>*/}
            {/*                <img width={15} height={15} src={require('../img/Avatar.png')}/>*/}
            {/*            <div>Arco Design</div>*/}
            {/*        </div>*/}
            {/*    </div>*/}
            {/*</div>*/}


        }

        return items;




    }



    //先修课程
    function xxkcInit(){
        const params = {
            bizId:info.id,
            relationType:0,
            pageNum:xxkcpage.pageNum,
            pageSize:xxkcpage.pageSize
        }
        schCourseRef(params).then(res=>{
            setxxkcList(res.data)
        })
    }

    function xxkclistApp(){
        const item = []

        for(let i=0;i<xxkcList.list.length;i++){

            item.push(

                <Trigger
                    key={i}
                    popup={() =>

                        <div className={styles.del}>
                            <div  onClick={()=>
                                openMenu({id:xxkcList.list[i].bizId,schCourseId:xxkcList.list[i].schCourseId,bizType:xxkcList.list[i].bizType,name:xxkcList.list[i].name})
                            }>查看</div>
                            <div onClick={()=>{
                                del({relationId:xxkcList.list[i].relationId}).then(()=>{
                                    xxkcInit()
                                })
                            }
                            }>移除依赖</div>
                        </div>

                    }
                    mouseEnterDelay={400}
                    mouseLeaveDelay={400}
                    position='bottom'
                    trigger={'contextMenu'}
                >
                    <div className={styles.xxkcGridItem}>
                        <div>
                            <img width={30} height={30} src={require('../img/book.png')} alt=""/>
                            <div>{xxkcList.list[i].name}</div>
                        </div>
                        <div>
                            <div>
                                章节：{xxkcList.list[i].chapterNum}
                            </div>
                            <div>
                                知识：{xxkcList.list[i].knowledgeFirstNum+xxkcList.list[i].knowledgeSecondNum}
                            </div>
                            <div>
                                资料：{xxkcList.list[i].resourceNum}
                            </div>

                        </div>
                        <img src={require('../img/Vector.png')} className={styles.icon} alt=""  />

                    </div>
                </Trigger>




            )


        }

        return (
            <div className={styles.xxkcGrid}>
                {item}
            </div>

        )

    }

    //左侧课程list
    const [kcList,setkcList] = useState([])
    //左侧知识点list
    const [zsdList,setZsdList] = useState([])

    function otherSearch(text:string){
        let name:string
        return ( <div className={styles.search}>
            <div className={styles.searchTitle}>{text}</div>
            {addLeft()}
            <Input style={{ width: 350 }}
                   onChange={e=>name=e}
                   addAfter={<Button type={"primary"}  shape={"round"}

                                     onClick={()=>{
                                         if (text.indexOf('课程')!==-1){
                                             getLessonAllApi({name:name}).then(res=>{
                                                 setkcList(res.data)
                                             })
                                         }}}
                   >搜索</Button>} placeholder='请输入关键词' />
        </div>)

    }
    // 左侧课程
    function addLeft(){

        return  kcList.map((item:any,index:number)=>{
            return (
                <div style={{display:'flex',alignItems:'center',width:'100%'}} key={index}>
                    <div className={styles.kcItem} >
                        <div>
                            <img width={30} height={30} src={require('../img/book.png')} alt=""/>
                            <div>{item.value}</div>
                        </div>
                        <div>
                            <div>
                                章节：131
                            </div>
                            <div>
                                知识：131
                            </div>
                            <div>
                                资料：12123
                            </div>
                        </div>
                    </div>
                    <div>
                        <IconPlusCircle width={16} height={16} style={{cursor:'pointer',marginLeft:'4px'}}
                                        onClick={()=>{
                                            schCourseRefInsert({bizId:info.id,refIdList:[item.key]}).then(res=>{
                                                xxkcInit()
                                            })
                                        }}
                        />
                    </div>
                </div>
            )

        })


    }


    //支撑课程
    function zckcInit(){
        const params = {
            bizId:info.id,
            relationType:1,
            pageNum:zckc.pageNum,
            pageSize:zckc.pageSize
        }
        schCourseRef(params).then(res=>{
            setzxkcList(res.data)
        })
    }

    function zckcListApp(){
        const item = []
        for(let i=0;i<zckcList.list.length;i++){

            item.push
            (
                <Trigger
                    key={i}
                    popup={() =>

                        <div className={styles.del}>
                            <div  onClick={()=>
                                openMenu({id:zckcList.list[i].bizId,schCourseId:zckcList.list[i].schCourseId,bizType:zckcList.list[i].bizType,name:zckcList.list[i].name})
                            }>查看</div>
                            <div onClick={()=>{
                                del({relationId:zckcList.list[i].relationId}).then(()=>{
                                    zckcInit()
                                })
                            }
                            }>移除依赖</div>
                        </div>
                    }
                    mouseEnterDelay={400}
                    mouseLeaveDelay={400}
                    position='bottom'
                    trigger={'contextMenu'}
                >
                    <div  className={styles.xxkcGridItem}>
                        <div>
                            <img width={30} height={30} src={require('../img/book.png')} alt=""/>
                            <div>{zckcList.list[i].name}</div>
                        </div>
                        <div>
                            <div>
                                章节：{zckcList.list[i].chapterNum}
                            </div>
                            <div>
                                知识：{zckcList.list[i].knowledgeFirstNum+zckcList.list[i].knowledgeSecondNum}
                            </div>
                            <div>
                                资料：{zckcList.list[i].resourceNum}
                            </div>

                        </div>
                        <img src={require('../img/Vector.png')} className={styles.icon} alt=""  />
                    </div>
                </Trigger>
            )


        }

        return (
            <div className={styles.xxkcGrid}>
                {item}
            </div>

        )

    }


    function otherzckcSearch(text:string){
        let name:string
        return ( <div className={styles.search}>
            <div className={styles.searchTitle}>{text}</div>
            {addzckcLeft()}
            <Input style={{ width: 350 }}
                   onChange={e=>name=e}
                   addAfter={<Button type={"primary"}  shape={"round"}

                                     onClick={()=>{
                                         if (text.indexOf('课程')!==-1){
                                             getLessonAllApi({name:name}).then(res=>{
                                                 setkcList(res.data)
                                             })
                                         }}}
                   >搜索</Button>} placeholder='请输入关键词' />
        </div>)

    }


    function addzckcLeft(){

        return  kcList.map((item:any,index:number)=>{
            return (
                <div style={{display:'flex',alignItems:'center',width:'100%'}} key={index}>
                    <div className={styles.kcItem} >
                        <div>
                            <img width={30} height={30} src={require('../img/book.png')} alt=""/>
                            <div>{item.value}</div>
                        </div>
                        <div>
                            <div>
                                章节：131
                            </div>
                            <div>
                                知识：131
                            </div>
                            <div>
                                资料：12123
                            </div>
                        </div>
                    </div>
                    <div>
                        <IconPlusCircle width={16} height={16} style={{cursor:'pointer',marginLeft:'4px'}}
                                        onClick={()=>{
                                            schCourseRefInsertSupport({bizId:info.id,refIdList:[item.key]}).then(res=>{
                                                zckcInit()
                                            })
                                        }}
                        />
                    </div>
                </div>
            )

        })


    }
    //支撑课程结束

    //应用关系知识开始


    function yygxzsInit(){

        const params = {
            bizId:info.id,
            relationType:info.bizType===2?2:4,
            pageNum:yygxzx.pageNum,
            pageSize:yygxzx.pageSize
        }
        schCourseRef(params).then(res=>{
            setyygxzxList(res.data)
        })
    }
    function yygxzsListApp(){
        const item = []
        for(let i=0;i<yygxzxList.list.length;i++){

            item.push(

                <Trigger
                    key={i}
                    popup={() =>
                        <div className={styles.del}>
                            <div  onClick={()=>
                                openMenu({id:yygxzxList.list[i].bizId,schCourseId:yygxzxList.list[i].schCourseId,bizType:yygxzxList.list[i].bizType,name:yygxzxList.list[i].name})
                            }>查看</div>
                            <div onClick={()=>{
                                del({relationId:yygxzxList.list[i].relationId}).then(()=>{
                                    yygxzsInit()
                                })
                            }
                            }>移除依赖</div>
                        </div>
                    }
                    mouseEnterDelay={400}
                    mouseLeaveDelay={400}
                    position='bottom'
                    trigger={'contextMenu'}
                >
                    <div  className={styles.xxkcGridItem}>
                        <div>
                            <img width={30} height={30} src={require('../img/zhishi.png')} alt=""/>
                            <div>{yygxzxList.list[i].name}</div>
                        </div>
                        <div>
                            <div>
                                资料：{yygxzxList.list[i].resourceNum}
                            </div>
                            <div style={{whiteSpace:'nowrap'}}>
                                更新时间:{yygxzxList.list[i].updateTime}
                            </div>
                        </div>
                        <img src={require('../img/Vector.png')} className={styles.icon} alt=""  />
                    </div>
                </Trigger>
            )


        }

        return (
            <div className={styles.xxkcGrid}>
                {item}
            </div>

        )

    }
    function otheryygxzsSearch(text:string){
        let name:string
        return ( <div className={styles.search}>
            <div className={styles.searchTitle}>{text}</div>
            <div style={{width:'100%'}}>
                {addyyzsLeft()}
            </div>
            <Input style={{ width: 350 }}
                   onChange={e=>name=e}
                   addAfter={<Button type={"primary"}  shape={"round"}

                                     onClick={()=>{
                                         if (text.indexOf('知识')!==-1){
                                             if (info.bizType===2){
                                                 searchCourseKnowledge({pageNum:1,pageSize:1000}).then(res=>{
                                                     setZsdList(res.data.list)
                                                 })
                                             }else {
                                                 searchCourseKnowledgeSecond({pageNum:1,pageSize:1000}).then(res=>{
                                                     setZsdList(res.data.list)
                                                 })
                                             }
                                         }}}
                   >搜索</Button>} placeholder='请输入关键词' />
        </div>)

    }
    function addyyzsLeft(){

        return  zsdList.map((item:any,index:number)=>{
            return (
                <div style={{display:'flex',alignItems:'center',width:'100%'}} key={index}>
                    <div className={styles.kcItem} >
                        <div>
                            <img width={30} height={30} src={require('../img/book.png')} alt=""/>
                            <div>{item.name}</div>
                        </div>
                        <div>
                            <div>
                                资料：{item.countMsg.resourceNum}
                            </div>
                            <div>
                                更新时间：{item.updateTime}
                            </div>
                        </div>
                    </div>
                    <div>
                        <IconPlusCircle width={16} height={16} style={{cursor:'pointer',marginLeft:'4px'}}
                                        onClick={()=>{
                                            if (info.bizType===2){
                                                schCourseRefInsertKnowledgeApplyFirst({bizId:info.id,refIdList:[{refType:2,refId:item.id}]}).then(()=>{
                                                    ylzsgxInit()
                                                })
                                            }else{
                                                schCourseRefInsertKnowledgeApplySecond({bizId:info.id,refIdList:[{refType:2,refId:item.id}]}).then(()=>{
                                                    yygxzsInit()
                                                })
                                            }



                                        }}
                        />
                    </div>
                </div>
            )

        })


    }
    //应用关系知识结束

    //依赖关系知识
    function ylzsgxInit(){
        const params = {
            bizId:info.id,
            relationType:info.bizType===2?3:5,
            pageNum:yygxzx.pageNum,
            pageSize:yygxzx.pageSize
        }
        schCourseRef(params).then(res=>{
            setylgxzxList(res.data)
        })
    }
    function ylzsListApp(){
        const item = []
        for(let i=0;i<ylgxzxList.list.length;i++){

            item.push(
                <Trigger
                    key={i}
                    popup={() =>
                        <div className={styles.del}>
                            <div  onClick={()=>
                                openMenu({id:ylgxzxList.list[i].bizId,schCourseId:ylgxzxList.list[i].schCourseId,bizType:ylgxzxList.list[i].bizType,name:ylgxzxList.list[i].name})
                            }>查看</div>
                            <div onClick={()=>{
                                del({relationId:ylgxzxList.list[i].relationId}).then(()=>{
                                    ylzsgxInit()
                                })
                            }
                            }>移除依赖</div>
                        </div>
                    }
                    mouseEnterDelay={400}
                    mouseLeaveDelay={400}
                    position='bottom'
                    trigger={'contextMenu'}
                >

                    <div  className={styles.xxkcGridItem}>
                        <div>
                            <img width={30} height={30} src={require('../img/zhishi.png')} alt=""/>
                            <div>{ylgxzxList.list[i].name}</div>
                        </div>
                        <div>

                            <div>
                                资料：{ylgxzxList.list[i].resourceNum}
                            </div>
                            <div style={{whiteSpace:'nowrap'}}>
                                更新时间:{ylgxzxList.list[i].updateTime}
                            </div>
                        </div>
                        <img src={require('../img/Vector.png')} className={styles.icon} alt=""  />
                    </div>
                </Trigger>
            )


        }

        return (
            <div className={styles.xxkcGrid}>
                {item}
            </div>

        )

    }

    function otherylzsSearch(text:string){
        let name:string
        return ( <div className={styles.search}>
            <div className={styles.searchTitle}>{text}</div>
            {addylzsLeft()}
            <Input style={{ width: 350 }}
                   onChange={e=>name=e}
                   addAfter={<Button type={"primary"}  shape={"round"}

                                     onClick={()=>{
                                         if (text.indexOf('知识')!==-1){
                                             if (info.bizType===2){
                                                 searchCourseKnowledge({pageNum:1,pageSize:1000}).then(res=>{
                                                     setZsdList(res.data.list)
                                                 })
                                             }else {
                                                 searchCourseKnowledgeSecond({pageNum:1,pageSize:1000}).then(res=>{
                                                     setZsdList(res.data.list)
                                                 })
                                             }
                                         }}}
                   >搜索</Button>} placeholder='请输入关键词' />
        </div>)

    }
    function addylzsLeft(){
        return  zsdList.map((item:any,index:number)=>{
            return (
                <div style={{display:'flex',alignItems:'center',width:'100%'}} key={index}>
                    <div className={styles.kcItem} >
                        <div>
                            <img width={30} height={30} src={require('../img/book.png')} alt=""/>
                            <div>{item.name}</div>
                        </div>
                        <div>
                            <div>
                                资料：{item.countMsg.resourceNum}
                            </div>
                            <div>
                                更新时间：{item.updateTime}
                            </div>
                        </div>
                    </div>
                    <div>
                        <IconPlusCircle width={16} height={16} style={{cursor:'pointer',marginLeft:'4px'}}
                                        onClick={()=>{
                                            if (info.bizType===2){
                                                schCourseRefInsertKnowledgeDependsFirst({bizId:info.id,refIdList:[{refType:2,refId:item.id}]}).then(()=>{
                                                    ylzsgxInit()
                                                })
                                            }else{
                                                schCourseRefInsertKnowledgeDependsSecond({bizId:info.id,refIdList:[{refType:2,refId:item.id}]}).then(()=>{
                                                    ylzsgxInit()
                                                })
                                            }
                                        }}
                        />
                    </div>
                </div>
            )

        })


    }
    //依赖关系结束
    //树相关
    const [selectNode, setSelectNode] = useState({});
    const [newSectionName, setNewSectionName] = useState('');
    const [visibleInput, setVisibleInput] = useState(false);
    const addKnowledge = (info) => {
        addKnowledgeApi(info)
            .then((res) => {
                const { msg } = res;
                Message.success(msg);
                fetchTreeData();
            })
            .catch((e) => {
                console.log(e);
            });
    };

    const editKnowledge = (info) => {
        editKnowledgeApi(info)
            .then((res) => {
                const { msg } = res;
                Message.success(msg);
                fetchTreeData();
            })
            .catch((e) => {
                console.log(e);
            });
    };
    const deleteKnowledge = (id) => {
        deleteKnowledgeApi({ id: id })
            .then((res) => {
                const { msg } = res;
                Message.success(msg);
                fetchTreeData();
            })
            .catch((e) => {
                console.log(e);
            });
    };
    const fetchTreeData = () => {
        getSectionApi({
            schCourseId: info.schCourseId,
            pageNum: 1,
            pageSize: 100,
        })
            .then((res) => {
                const { data } = res;
                setTreeData(data.list);
            })
            .catch((e) => {
                console.log(e);
            });
    };

    const loadMore = (treeNode) => {
        return getKnowledgeApi({
            schCourseId: info.schCourseId,
            schCourseChapterId: treeNode.props.dataRef.id,
            pageNum: 1,
            pageSize: 100,
            type: treeNode.props.dataRef.type === 0 ? 1 : 0,
        })
            .then((res) => {
                const { data } = res;
                treeNode.props.dataRef.children = data.list;
                setTreeData([...treeData]);
            })
            .catch((e) => {
                console.log(e);
            });
    };
    const addSection = () => {
        addSectionApi({ schCourseId: info.schCourseId, name: newSectionName })
            .then((res) => {
                const { msg } = res;
                Message.success(msg);
                fetchTreeData();
            })
            .catch((e) => {
                console.log(e);
            });
    };

    const deleteSection = (id) => {
        deleteSectionApi({ id: id })
            .then((res) => {
                const { msg } = res;
                Message.success(msg);
                fetchTreeData();
            })
            .catch((e) => {
                console.log(e);
            });
    };

    const editSection = (info) => {
        editSectionApi(info)
            .then((res) => {
                const { msg } = res;
                Message.success(msg);
                fetchTreeData();
            })
            .catch((e) => {
                console.log(e);
            });
    };
    return(
        <div >
            <Drawer
                width={'70%'}
                title={<div className={styles.title}><Tag color={'#7816ff'} bordered>{text[info.bizType]}</Tag><span style={{marginLeft:'15px'}}>{info.name}</span></div> }
                visible={visible}
                footer={null}
                onOk={() => {
                    setVisible(false);
                }}
                onCancel={() => {
                    setVisible(false);
                }}
                unmountOnExit={true}
            >
                <div className={styles.container}>
                    <Tabs defaultActiveTab={defaultActiveTab}>
                        <TabPane key='1' title='课程体系'>
                            <div style={{ width: '90%', padding: 2, overflow: 'auto',margin:'25px' }}>
                                <Row>
                                    <Col span={12}>
                                        {/*    <Tree*/}
                                        {/*    blockNode*/}
                                        {/*    defaultSelectedKeys={[String(info.id)]}*/}
                                        {/*    defaultExpandedKeys={[String(info.id)]}*/}
                                        {/*>*/}
                                        {/*    {generatorTreeNodes(treeData)}*/}
                                        {/*</Tree>*/}
                                        <Space>
                                            <div style={{fontSize:"14px",fontWeight:'bold'}}>课程章节</div>
                                            <Popover
                                                position={'right'}
                                                title="课程章节"
                                                popupVisible={visibleInput} // button 触发 mouseenter的时候会调用该方法。更多的用法可以查看Trigger组件。
                                                content={
                                                    <span>
                                         <Input
                                             allowClear
                                             placeholder={`章节名称`}
                                             onChange={(value) => {
                                                 setNewSectionName(value);
                                             }}
                                         />
                                      <Space align={'end'} style={{ marginTop: 10 }}>
                                        <Link
                                            onClick={() => {
                                                setVisibleInput(false);
                                            }}
                                        >
                                          取消
                                        </Link>
                                        <Link onClick={() => addSection()}>增加</Link>
                                      </Space>
                                    </span>
                                                }
                                            >
                                                <Button
                                                    size={'small'}
                                                    icon={<IconPlus />}
                                                    style={{
                                                        fontSize: 12,
                                                        color: '#3370ff',
                                                        backgroundColor: '#ffffff',
                                                    }}
                                                    onClick={() => {
                                                        setVisibleInput(true);
                                                    }}
                                                ></Button>
                                            </Popover>
                                        </Space>
                                        <Tree
                                            fieldNames={{
                                                key: 'createTime',
                                                title: 'name',
                                                children: 'children',
                                            }}
                                            loadMore={loadMore}
                                            showLine={true}
                                            treeData={treeData}
                                            onSelect={(keys, extra) => {
                                                setSelectNode(extra.node.props.dataRef);
                                            }}
                                            renderExtra={(node) => {
                                                return (
                                                    <div>
                                                        {node.dataRef.type !== 1 ? (
                                                            <Popover
                                                                title={null}
                                                                popupVisible={node.dataRef.visiblePlus} // button 触发 mouseenter的时候会调用该方法。更多的用法可以查看Trigger组件。
                                                                content={
                                                                    <span>
                          <Input
                              allowClear
                              onChange={(value) => {
                                  node.dataRef.inputValue = value;
                              }}
                          />
                          <Space align={'end'} style={{ marginTop: 10 }}>
                            <Link
                                onClick={() => {
                                    node.dataRef.visiblePlus = false;
                                    setTreeData([...treeData]);
                                }}
                            >
                              取消
                            </Link>
                            <Link
                                onClick={() => {
                                    addKnowledge({
                                        schCourseChapterId: node.dataRef.id,
                                        name: node.dataRef.inputValue,
                                        type: node.dataRef.type === 0 ? 1 : 0,
                                    });
                                }}
                            >
                              增加
                            </Link>
                          </Space>
                        </span>
                                                                }
                                                            >
                                                                <Button
                                                                    size={'mini'}
                                                                    style={{
                                                                        position: 'absolute',
                                                                        right: 50,
                                                                        fontSize: 12,
                                                                        top: 5,
                                                                        color: '#3370ff',
                                                                        backgroundColor: '#ffffff',
                                                                    }}
                                                                    icon={<IconPlus />}
                                                                    onClick={() => {
                                                                        node.dataRef.visiblePlus = true;
                                                                        setTreeData([...treeData]);
                                                                    }}
                                                                ></Button>
                                                            </Popover>
                                                        ) : null}

                                                        <Popover
                                                            title="修改"
                                                            popupVisible={node.dataRef.visible} // button 触发 mouseenter的时候会调用该方法。更多的用法可以查看Trigger组件。
                                                            content={
                                                                <span>
                        <Input
                            allowClear
                            placeholder={`${node.dataRef.name}`}
                            onChange={(value) => {
                                node.dataRef.inputValue = value;
                            }}
                        />
                        <Space align={'end'} style={{ marginTop: 10 }}>
                          <Link
                              onClick={() => {
                                  node.dataRef.visible = false;
                                  setTreeData([...treeData]);
                              }}
                          >
                            取消
                          </Link>
                          <Link
                              onClick={() => {
                                  console.log(node, 'edit');
                                  if (node.dataRef.type > -1) {
                                      editKnowledge({
                                          id: node.dataRef.id,
                                          name: node.dataRef.inputValue,
                                      });
                                  } else {
                                      editSection({
                                          id: node.dataRef.id,
                                          name: node.dataRef.inputValue,
                                      });
                                  }
                              }}
                          >
                            修改
                          </Link>
                        </Space>
                      </span>
                                                            }
                                                        >
                                                            <Button
                                                                size={'mini'}
                                                                style={{
                                                                    position: 'absolute',
                                                                    right: 30,
                                                                    fontSize: 12,
                                                                    top: 5,
                                                                    color: '#3370ff',
                                                                    backgroundColor: '#ffffff',
                                                                }}
                                                                icon={<IconAlignLeft />}
                                                                onClick={() => {
                                                                    node.dataRef.visible = true;
                                                                    setTreeData([...treeData]);
                                                                }}
                                                            ></Button>
                                                        </Popover>
                                                        <Popconfirm
                                                            focusLock
                                                            icon={null}
                                                            title="确定删除吗?"
                                                            onOk={() => {
                                                                if (node.dataRef.type > -1) {
                                                                    deleteKnowledge(node.dataRef.id);
                                                                } else {
                                                                    deleteSection(node.dataRef.id);
                                                                }
                                                            }}
                                                        >
                                                            <Button
                                                                style={{
                                                                    position: 'absolute',
                                                                    right: 6,
                                                                    fontSize: 12,
                                                                    top: 5,
                                                                    color: '#3370ff',
                                                                    backgroundColor: '#ffffff',
                                                                }}
                                                                size={'mini'}
                                                                icon={<IconDelete />}
                                                                onClick={() => {
                                                                    setTreeData([...treeData]);
                                                                }}
                                                            ></Button>
                                                        </Popconfirm>
                                                    </div>
                                                );
                                            }}
                                        ></Tree>
                                    </Col>
                                    <Col span={12}><Descriptions border data={data} column={1} style={{paddingLeft:'31px'}} /> </Col>
                                </Row>
                            </div>
                        </TabPane>
                        <TabPane key='2' title='知识图谱' >
                            <div
                                style={{padding:'25px',width:'100%'}}
                            >
                                <Map />
                            </div>
                        </TabPane>
                        <TabPane key='3' title='资料库'>
                            <div
                                style={{padding:'25px 0 0 25px',position:"relative"}}
                                ref={refWrapper}
                            >
                                <div style={{width:'95%'}}>
                                    <Row>
                                        <Col span={6}>
                                            <div className={styles.leftMenu} >
                                                {menuLeft()}
                                                <Modal
                                                    alignCenter={false}
                                                    style={{ top:400,left:-335,width:'300px',height:'500px' } }
                                                    title={
                                                        <div style={{textAlign:'left'}}>正在上传（{uploadList.length}）</div>
                                                    }
                                                    mask={false}
                                                    visible={modelVisible}
                                                    onOk={() => setModelVisible(false)}
                                                    onCancel={() => setModelVisible(false)}
                                                    autoFocus={false}
                                                    focusLock={true}
                                                    footer={null}
                                                    getPopupContainer={() => refWrapper && refWrapper.current}
                                                >
                                                    {uploadList.map((file, index) => {
                                                        return(
                                                            <div key={index} className={styles.fileList}>
                                                                <div>
                                                                    <img src={require('../img/P.png')}/>
                                                                    <div>
                                                                        {file.name}
                                                                    </div>
                                                                </div>
                                                                <div >
                                                                    <div>{file.percent}%</div>
                                                                    <Progress
                                                                        size='mini'
                                                                        percent={file.percent}
                                                                    />
                                                                </div>
                                                            </div>
                                                        )
                                                    })}
                                                </Modal>
                                                <div className={styles.upload}>
                                                    {uploadList.length>0&&(<div className={styles.uploading}  onClick={()=>{
                                                        setModelVisible(!modelVisible)
                                                    }}>
                                                        <img src={require('../img/uploadIng.png')} alt=""  />
                                                        <div >正在上传（{uploadList.length}）</div>
                                                    </div>)}
                                                    <Upload action='http://101.200.84.209:10000/api/fileStore/upload'
                                                            multiple
                                                            headers={{ Authorization: token }}
                                                            showUploadList={true}
                                                            onProgress={(file) => {
                                                                setUploadList((v) => {
                                                                    return v.map((x) => {
                                                                        return x.uid === file.uid ? file : x;
                                                                    });
                                                                });
                                                            }}
                                                            onChange={(fileList, file:any)=>{
                                                                if (file.response){
                                                                    const params = {
                                                                        bizType:info.bizType,
                                                                        bizId:info.bizType!==0?info.id:info.schCourseId,
                                                                        resourceType:0,
                                                                        key:file.response.data.fileKey,
                                                                        name:file.response.data.fileName,
                                                                        size:file.response.data.size,
                                                                        suffix:file.response.data.suffix,
                                                                    }
                                                                    schCourseResourceInsert(params).then(res=>{
                                                                        setUploadList((v) => {
                                                                            return v.filter((x) => x.uid !== file.uid);
                                                                        });
                                                                        requestData()
                                                                    })
                                                                }else {
                                                                    setUploadList(fileList)
                                                                }
                                                            }}
                                                            fileList={uploadList}
                                                    >上传资料</Upload>
                                                </div>

                                            </div>

                                        </Col>
                                        <Col span={12}>
                                            <Row>
                                                <Col span={14}>
                                                    <InputSearch
                                                        searchButton='搜索'
                                                        placeholder='请输入关键词搜索'
                                                        onSearch={(value) => {
                                                            setPage((prevPage) => ({
                                                                ...prevPage,
                                                                name: value
                                                            }));
                                                        }}
                                                    />
                                                </Col>

                                            </Row>
                                            <div className={styles.main}>

                                                <div className={styles.gridContainer}>
                                                    {list()}
                                                </div>

                                            </div>

                                            <div style={{display:"flex",justifyContent:"flex-end",marginTop:'15px'}}>
                                                <Pagination   total={resource.total} showTotal pageSize={page.pageSize}  sizeCanChange={false} onChange={(pageNumber,pageSize)=>{
                                                    setPage((prevPage) => ({
                                                        ...prevPage,
                                                        pageNumber:pageNumber,
                                                    }))
                                                }} />
                                            </div>
                                        </Col>
                                        <Col span={4}>
                                            <div style={{textAlign:'right'}}>
                                                <Dropdown droplist={dropList} trigger='click' position='br' >
                                                    <Button type='text'>
                                                        仅查看此节点
                                                        <IconDown />
                                                    </Button>
                                                </Dropdown>
                                            </div>

                                        </Col>
                                    </Row>



                                </div>

                            </div>


                        </TabPane>
                        {info.bizType==0&&(<TabPane key='4' title='先修课程'>
                            <div className={styles.xxkc}>
                                <div className={styles.title}>该课程有以下先修课程</div>
                                <div style={{minHeight:'60vh'}}>
                                    {xxkclistApp()}
                                </div>

                                <div className={styles.otherFooter}>
                                    <Trigger  popup={() => (
                                        <div>
                                            {  otherSearch('查找先修课程')}
                                        </div>)}
                                              trigger='click' position='top'
                                              popupAlign={{
                                                  top:[40,18.5],
                                              }}
                                    >
                                        <Button type='primary'  >添加</Button>
                                    </Trigger>
                                    <Pagination  total={xxkcList.total} showTotal  sizeCanChange={false} onChange={(pageNumber,pageSize)=>{
                                        setxxkcPage((prevPage) => ({
                                            ...prevPage,
                                            pageNumber:pageNumber,
                                            pageSize:pageSize
                                        }))
                                    }} />
                                </div>
                            </div>
                        </TabPane>)}
                        {info.bizType==0&&(<TabPane key='5' title='支撑课程'>
                            <div className={styles.xxkc}>
                                <div className={styles.title}>该课程有以下支撑课程</div>
                                <div style={{minHeight:'60vh'}}>
                                    {zckcListApp()}
                                </div>

                                <div className={styles.otherFooter}>
                                    <Trigger  popup={() => (
                                        <div>
                                            {  otherzckcSearch('查找支撑课程')}
                                        </div>)}
                                              trigger='click' position='top'
                                              popupAlign={{
                                                  top:[40,18.5],
                                              }}
                                    >
                                        <Button type='primary'  >添加</Button>
                                    </Trigger>
                                    <Pagination  total={zckcList.total} showTotal  sizeCanChange={false} onChange={(pageNumber,pageSize)=>{
                                        setzckcPage((prevPage) => ({
                                            ...prevPage,
                                            pageNumber:pageNumber,
                                            pageSize:pageSize
                                        }))
                                    }} />
                                </div>
                            </div>
                        </TabPane>)}
                        {(info.bizType==2||info.bizType==3)&&( <TabPane key='6' title='应用关系知识' closable={true}>
                            <div className={styles.xxkc}>
                                <div className={styles.title}>该课程有以下先修课程</div>
                                <div style={{minHeight:'60vh'}}>
                                    {yygxzsListApp()}
                                </div>

                                <div className={styles.otherFooter}>
                                    <Trigger  popup={() => (
                                        <div>
                                            {  otheryygxzsSearch('查找先应用关系知识')}
                                        </div>)}
                                              trigger='click' position='top'
                                              popupAlign={{
                                                  top:[40,18.5],
                                              }}
                                    >
                                        <Button type='primary'  >添加</Button>
                                    </Trigger>
                                    <Pagination  total={yygxzxList.total} showTotal  sizeCanChange={false} onChange={(pageNumber,pageSize)=>{
                                        setyygxzx((prevPage) => ({
                                            ...prevPage,
                                            pageNumber:pageNumber,
                                            pageSize:pageSize
                                        }))
                                    }} />
                                </div>
                            </div>
                        </TabPane>)}
                        {(info.bizType==2||info.bizType==3)&&(<TabPane key='7' title='依赖关系知识'>
                            <div className={styles.xxkc}>
                                <div className={styles.title}>该课程有以下先修课程</div>
                                <div style={{minHeight:'60vh'}}>
                                    {ylzsListApp()}
                                </div>

                                <div className={styles.otherFooter}>
                                    <Trigger  popup={() => (
                                        <div>
                                            {  otherylzsSearch('查找依赖关系知识')}
                                        </div>)}
                                              trigger='click' position='top'
                                              popupAlign={{
                                                  top:[40,18.5],
                                              }}
                                    >
                                        <Button type='primary'  >添加</Button>
                                    </Trigger>
                                    <Pagination  total={ylgxzxList.total} showTotal  sizeCanChange={false} onChange={(pageNumber,pageSize)=>{
                                        setylgxzxPage((prevPage) => ({
                                            ...prevPage,
                                            pageNumber:pageNumber,
                                            pageSize:pageSize
                                        }))
                                    }} />
                                </div>
                            </div>
                        </TabPane>)}
                    </Tabs>
                </div>
            </Drawer>
            {/*<DetailDrawer ref={detailRef} />*/}
        </div>

    )
})



export default Detail
